package com.goalias.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.goalias.domain.ChatRequest;
import com.goalias.domain.dto.ChatParam;
import com.goalias.exception.BizException;
import com.goalias.properties.ChatProperties;
import com.goalias.service.IChatService;
import com.goalias.utils.AESUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class TyChatServiceImpl implements IChatService {

    @Resource
    private ChatProperties chatProperties;


    @Override
    public String getAccessKey() {
        String accessKey = "";
        try {
            accessKey = AESUtils.decrypt(chatProperties.getTyAccessKey());
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
        return accessKey;
    }

    @Override
    public String getCheerWord(String tyAccessKey) {
        ChatParam cheerParam = new ChatParam(
                chatProperties.getIntentModel(), tyAccessKey, chatProperties.getCheerSystemPrompt(),
                chatProperties.getCheerInput());
        return sendChat(cheerParam);
    }
    @Override
    public String getKnowledgeWord(String tyAccessKey) {
        ChatParam cheerParam = new ChatParam(
                chatProperties.getChatModel(), tyAccessKey, chatProperties.getKnowledgeSystemPrompt(),
                chatProperties.getKnowledgeInput());
        return sendChat(cheerParam);
    }

    private String sendChat(ChatParam chatParam) {
        HttpRequest httpRequest = HttpUtil.createPost(chatProperties.getTyChatUrl());
        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setModel(chatParam.getModel());
        chatRequest.setTop_p(1);
        chatRequest.setPresence_penalty(2);
        List<ChatRequest.Message> messages = new ArrayList<>();
        messages.add(new ChatRequest.Message("system", chatParam.getSystemPrompt()));
        messages.add(new ChatRequest.Message("user", chatParam.getInput()));
        chatRequest.setMessages(messages);
        HttpResponse httpResponse = httpRequest.bearerAuth(chatParam.getAccessKey())
                .body(JSONUtil.toJsonStr(chatRequest))
                .contentType("application/json")
                .execute();
        String body = httpResponse.body();
        if(!StringUtils.hasText(body)){
            throw new BizException("发送请求chat失败");
        }
        JSONObject jsonObject = new JSONObject(body);
        if (jsonObject.get("choices") == null){
            throw new BizException("请求chat非法error");
        }
        return jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getStr("content");
    }
}
